import cv2 as cv
import numpy as np

#检测目标轮廓
#U,L,B：分别为矩形长宽比值上下限，轮廓面积下限
def findContours(img,U,L,B):
    #将图像转到HSV色彩空间
    hsv_img = cv.cvtColor(img, cv.COLOR_BGR2HSV)

    #不同颜色的不同HSV参数
    #蓝色
    #low_light = np.array([50, 43, 200])
    #high_light = np.array([130, 255, 255])
    #橙黄色
    low_light = np.array([11, 43, 46])
    high_light = np.array([34, 255, 255])
    #白色
    #low_light = np.array([0, 0, 221])
    #high_light = np.array([180, 43, 255])

    #根据HSV范围对图像二值化
    mask = cv.inRange(hsv_img, low_light, high_light)
    #寻找轮廓
    contours,hierarchy = cv.findContours(mask, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)
    #根据轮廓面积大小排序
    contours = sorted(contours, key=lambda x: cv.contourArea(x), reverse=True)
    
    
    i = 0
    box =[]#储存矩形对角两个点的坐标
    
    for cnt in contours:
        #获得矩形左上角点坐标及长宽
        (x, y, w, h) = cv.boundingRect(cnt)
        
        if w == 0 or h == 0:
            continue
        #最小面积
        elif  w*h <= B:
            continue
        #最小面积占比
        elif (int(cv.contourArea(cnt)))/(w*h) < 0.5:
            continue
        #长宽比
        elif h/w <= U and h/w >= L:
            box.append((x,y,x + w, y + h))
            i = i+1

    return box,i